/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tr.com.argela.tap.mot.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import tr.com.argela.tap.mot.dao.AuthenticationDao;
import tr.com.argela.tap.mot.dao.DbManager;
import tr.com.argela.tap.mot.dao.ModuleDao;
import tr.com.argela.tap.mot.dao.ProjectDao;
import tr.com.argela.tap.mot.logger.LoggerFactory;
import tr.com.argela.tap.mot.models.Module;
import tr.com.argela.tap.mot.models.Project;
import tr.com.argela.tap.mot.models.User;

/**
 * @author arge
 */
public class ModuleServlet extends HttpServlet {

    private static Logger logger = LoggerFactory.getLogger("servlets");

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * 
     * @param request
     *            servlet request
     * @param response
     *            servlet response
     * @throws ServletException
     *             if a servlet-specific error occurs
     * @throws IOException
     *             if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if (request.getParameter("module").equals("createmodule")) {

            createmodule(request, response);
        } else if (request.getParameter("module").equals("updatemodule")) {
            updatemodule(request, response);
        }
    }

    public void createmodule(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.info("Process request called");

        DbManager dbManager = new DbManager();

        try {
            String projectId = request.getParameter("pname");
            String moduleName = request.getParameter("modulename");

            String moduleDescription = request.getParameter("mdescription");
            String userId = request.getParameter("username");

            if (projectId != null && moduleDescription != null && moduleName != null && userId != null) {
                ModuleDao moduleDao = new ModuleDao();
                System.out.print("Module details" + moduleName + userId + moduleDescription + projectId);
                User user = new User();
                user.setId(Long.parseLong(userId));
                Project project = new Project();
                project.setId(Long.parseLong(projectId));
                int result = moduleDao.addModule(dbManager, moduleName, user, moduleDescription, project);
                Module module = null;
                if (result > 0) {
                    module = new Module();
                    module.setName(moduleName);
                    AuthenticationDao autDao = new AuthenticationDao();
                    user = autDao.getUserById(user.getId());
                    module.setUser(user);
                    ProjectDao projectDao = new ProjectDao();
                    project = projectDao.checkproject(project.getId());
                    module.setProject(project);
                    module.setDescription(moduleDescription);
                }
                request.getSession().setAttribute("module", module);

            }
            dbManager.commit();
        } catch (Exception e) {
            dbManager.rollback();
        } finally {
            dbManager.close();
        }
        response.sendRedirect("newModuleProperties.jsp");

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * 
     * @param request
     *            servlet request
     * @param response
     *            servlet response
     * @throws ServletException
     *             if a servlet-specific error occurs
     * @throws IOException
     *             if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * 
     * @param request
     *            servlet request
     * @param response
     *            servlet response
     * @throws ServletException
     *             if a servlet-specific error occurs
     * @throws IOException
     *             if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    public void updatemodule(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("Process request called");
        DbManager dbManager = new DbManager();

        try {
            ModuleDao moduleDao = new ModuleDao();
            Long moduleId = Long.parseLong(request.getParameter("moduleId"));
            String moduleName = request.getParameter("modulename");
            String moduleDescription = request.getParameter("moddescription");
            String userId = request.getParameter("username");
            User user = new User();
            user.setId(Long.parseLong(userId));
            String projectId = request.getParameter("pname");
            Project project = new Project();
            project.setId(Long.parseLong(projectId));

            System.out.print("module details" + moduleId + moduleName + moduleDescription + userId + projectId);
            int result = moduleDao.UpdateModule(dbManager, moduleId, moduleName, user, moduleDescription, project);
            Module module = null;
            if (result > 0) {
                module = new Module();
                module.setName(moduleName);
                AuthenticationDao autDao = new AuthenticationDao();
                user = autDao.getUserById(user.getId());
                module.setUser(user);
                ProjectDao projectDao = new ProjectDao();
                project = projectDao.checkproject(project.getId());
                module.setProject(project);
                module.setDescription(moduleDescription);
            }
            request.getSession().setAttribute("module", module);
            dbManager.commit();
        } catch (Exception e) {
            dbManager.rollback();
        } finally {
            dbManager.close();
        }

        response.sendRedirect("newModuleProperties.jsp");
    }

    /**
     * Returns a short description of the servlet.
     * 
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
